package cn.piggy.mail.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FolderUtil {

    private static final Logger logger = LoggerFactory.getLogger(FolderUtil.class);

    public static void zipFolder(String source, String destination) throws IOException {
        FileOutputStream fos = new FileOutputStream(destination);
        ZipOutputStream zos = new ZipOutputStream(fos);
        File file = new File(source);
        zipFile(file, file.getName(), zos);
        zos.close();
        fos.close();
    }

    private static void zipFile(File file, String filename, ZipOutputStream zos) throws IOException {
        if(file.isDirectory()){
            if(filename.endsWith("/")){
                zos.putNextEntry(new ZipEntry(filename));
            }else{
                zos.putNextEntry(new ZipEntry(filename+"/"));
            }
            zos.closeEntry();
            File[] files = file.listFiles();
            if(files!=null){
                for(File f: files){
                    zipFile(f, filename+"/"+f.getName(), zos);
                }
                return;
            }
        }
        FileInputStream fis = new FileInputStream(file);
        ZipEntry zipEntry = new ZipEntry(filename);
        zos.putNextEntry(zipEntry);
        byte[] bytes = new byte[4096];
        int length;
        while ((length = fis.read(bytes))>=0){
            zos.write(bytes, 0 , length);
        }
        zos.closeEntry();
        fis.close();
    }

    public static void deleteFolder(File folder){
        if(folder.isDirectory()){
            File[] files = folder.listFiles();
            if(files!=null){
                for (File file : files){
                    deleteFolder(file);
                }
            }
        }
        boolean delete = folder.delete();
        logger.info("folder delete is --> {}", delete);
    }
}
